package com.axend.aerosense.dev.viewmodel;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.utils.ThreadPoolUtils;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.entity.CheckFirmwareBean;
import com.axend.aerosense.dev.entity.DevUpdateResultBean;
import com.axend.aerosense.dev.entity.FirmwareInfoBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;

/**
 * Author: ChenHongWei
 * Date: 2021/3/3 17:41
 */
public class DevCheckUpdateViewModel extends CustomBaseViewModel<FirmwareInfoBean> {

    /**
     * 进度条走到99%的时间（s）
     */
    private static final int progressDelay = 60 * 10;

    /**
     * 页面状态：
     * 1：不需要升级
     * 2：需要升级
     * 3：升级中
     */
    public MutableLiveData<Integer> pagerState = new MutableLiveData<>(1);
    /** 进度 */
    public MutableLiveData<Integer> seekbarProgress = new MutableLiveData<>(0);
    /** 升级是否成功 */
    public MutableLiveData<Boolean> isUpdateSuccess = new MutableLiveData<>();

    private Disposable disposable;
    private String radarId;
    private volatile boolean run = true;
    private volatile boolean polling = false;

    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;

    public DevCheckUpdateViewModel(IBaseView baseViewImpl, ILoadDataResult<FirmwareInfoBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        ARouter.getInstance().inject(this);
    }

    public void setRadarId(String radarId) {
        this.radarId = radarId;
    }

    /**
     * 开始升级固件
     */
    public void startUpdate(){
//        ThreadPoolUtils.getInstance().execute(()->{
//            long delay = (long) ((progressDelay / 99f) * 1000f);
//            int count = 0;
//            while (count <= 99 && run){
//                try {
//                    TimeUnit.MILLISECONDS.sleep(delay);
//                    if (run){
//                        seekbarProgress.postValue(count);
//                        count++;
//                    }
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//            //超过等待时间，升级失败
//            if (count >= 99){
//                isUpdateSuccess.postValue(false);
//            }
//        });

        disposable = EasyHttp.post(UrlApi.URL.UpRadarFirmware.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(new CheckFirmwareBean(radarId)))
                .readTimeOut(progressDelay * 1000)
                .writeTimeOut(progressDelay * 1000)
                .connectTimeout(progressDelay * 1000)
                .execute(new SimpleCallBack<DevUpdateResultBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                        run = false;
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
//                        run = false;
//                        isUpdateSuccess.setValue(false);
                        pagerState.setValue(2);
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void onSuccess(DevUpdateResultBean bean) {
                        if (null == bean) return;

                        if (bean.isResult()){
                            isUpdateSuccess.setValue(true);
                        }else {
                            pollingUpgradeStatus();
                        }
                    }
                });
    }

    /**
     * 轮询雷达固件升级状态
     * 10秒一次
     */
    private void pollingUpgradeStatus(){
        if (polling) return;

        ThreadPoolUtils.getInstance().execute(()->{
            polling = true;
            while (polling){
                try {
                    TimeUnit.SECONDS.sleep(10);
                    if (!polling) break;

                    getUpgradeStatus();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getUpgradeStatus(){
        disposable = EasyHttp.post(UrlApi.URL.GetUpgradeStatus.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(new CheckFirmwareBean(radarId)))
                .execute(new SimpleCallBack<DevUpdateResultBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(DevUpdateResultBean bean) {
                        if (bean.isResult()){
                            isUpdateSuccess.setValue(true);
                        }
                    }
                });
    }

    //    public void downloadFile(Context context){
//        EasyHttp.downLoad(firmwareInfo.getRadarUrl())
//                .cacheMode(CacheMode.NO_CACHE)
//                .saveName(firmwareInfo.getVersion() + ".bin")
//                .savePath(Values.FIRMWARE_PATH)
//                .execute(new DownloadProgressCallBack<BaseStringBean>() {
//                    @Override
//                    public void update(long bytesRead, long contentLength, boolean done) {
//                        int temp = (int) ((float)bytesRead / contentLength * 100);
//                        count.setValue(temp);
//                        progressString.setValue(context.getString(R.string.dev_download_now) + "  " + temp + "%");
//                        if (done){
//                            isDownload.setValue(false);
//                            progress.setValue(false);
//                            downloadBtn.setValue(true);
//                        }
//                    }
//
//                    @Override
//                    public void onComplete(String path) {
//
//                    }
//
//                    @Override
//                    public void onStart() {
//
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        e.printStackTrace();
//                        ToastUtils.showShort(R.string.dev_download_failed);
//                        isDownload.setValue(true);
//                        progress.setValue(false);
//                        downloadBtn.setValue(true);
//                    }
//                });
//    }

    /**
     * 检查文件是否存在
     * true 不需要下载
     * false 需要下载
     * @param firmwareInfoBean
     * @return
     */
//    private boolean checkFile(FirmwareInfoBean firmwareInfoBean){
//        boolean bool = false;
//        File file = new File(Values.FIRMWARE_PATH);
//        LogUtils.d(file.toString());
//        if (file.exists()){
//            File[] fileList = file.listFiles();
//            for (File f : fileList){
//                if (getFileMD5(f).equals(firmwareInfoBean.getMD5().toUpperCase())){
//                    bool = true;
//                    break;
//                }
//            }
//        }else {
//            //路径不存在，创建文件夹
//            file.mkdirs();
//            bool = false;
//        }
//        return bool;
//    }

    /**
     * 获取文件MD5值
     * @return
     */
//    private String getFileMD5(File file) {
//        MessageDigest messagedigest = null;
//        try {
//            messagedigest = MessageDigest.getInstance("MD5");
//            FileInputStream in = new FileInputStream(file);
//            FileChannel ch = in.getChannel();
//            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
//                    file.length());
//            messagedigest.update(byteBuffer);
//            String md5 = ByteUtils.bytesToHexString(messagedigest.digest());
//            return md5;
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return "";
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            return "";
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "";
//        }
//    }

    @Override
    public void onLoad() {
        disposable = EasyHttp.post(UrlApi.URL.GetFirmwareVersion.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", iLoginService.getToken())
                .upJson(JsonUtil.toJson(new CheckFirmwareBean(radarId)))
                .execute(new SimpleCallBack<FirmwareInfoBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        loadDataFail(e.getMessage());
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(FirmwareInfoBean firmwareInfoBean) {
                        if (null != firmwareInfoBean)
                            loadDataSuccess(firmwareInfoBean);
                    }
                });
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null == disposable) return;

        run = false;
        polling = false;
        disposable.dispose();
    }
}
